package com.zh.webflux.dingding;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.zh.webflux.support.SpringContextHolder;

import java.util.List;

/**
 * 钉钉告警发送类
 * @author Goddess
 * @date 2023/9/22
 */
public final class DingDingSender {
    static final String ERROR_TAG = "[ERROR]\n";
    static final String INFO_TAG = "[INFO]\n";

    private static DingTalkClient client;

    private synchronized static void initClient(){
        if (client!=null) return;
        final String dingToken = SpringContextHolder.getPropertyOrThrow("ding_token");
        client =  new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token="+dingToken);
    }

    public static void noticeMessage(String content){
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(INFO_TAG+content);
        doSenderText(text);
    }
    public static void errorMessage(String content) {
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(ERROR_TAG+content);
        doSenderText(text);
    }

    private static void doSenderText(OapiRobotSendRequest.Text text){
        initClient();

        //消息
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("text");
        request.setText(text);

        //提醒谁@
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        at.setAtUserIds(List.of("manager7759"));
//        at.setIsAtAll(true);
        request.setAt(at);

        try {
            OapiRobotSendResponse response = client.execute(request);
            if(!response.isSuccess()) {
                throw new RuntimeException("钉钉告警信息发送未成功: "+response.getErrmsg());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
